package com.aube.plugin.wap;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.aube.plugin.origin.R;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.utils.AppUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UserUtil;
import com.ryg.dynamicload.DLBasePluginFragmentActivity;

/**
 * Created by huyaonan on 16/9/26.
 */
public class H5WrapperActivity extends DLBasePluginFragmentActivity {

    public static final String WEB_URL = "WEB_URL";
    public static final String WEB_TITLE = "WEB_TITLE";
    public static final String WEB_POST = "WEB_POST";

    private ImageView mShareWeiboImg, mShareWechatImg, mShareTimelineImg;
    private View mShareLayout, mShareWeibo, mShareWechat, mShareTimeline;

    private WebView mWeb;

    private View mTopbar;
    private TextView mTitle;
    private ImageView mBack;

    private H5ShareHelper mShareHelper;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_ad);

        mBack = (ImageView) findViewById(R.id.topbar_back);
        mBack.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_new_back));
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((mWeb != null && mWeb.canGoBack())) {
                    mWeb.goBack();
                    return;
                }
                finish();
            }
        });
        mTitle = (TextView) findViewById(R.id.topbar_title);

        String url = getIntent().getStringExtra(WEB_URL);
        String title = getIntent().getStringExtra(WEB_TITLE);
        boolean doPost = getIntent().getBooleanExtra(WEB_POST, false);
        if(StringUtils.isNotBlank(title))
            mTitle.setText(title);

        if(StringUtils.isBlank(url)) {
            finish();
            return;
        }

        mShareWeibo = findViewById(R.id.share_weibo);
        mShareWechat = findViewById(R.id.share_wechat);
        mShareTimeline = findViewById(R.id.share_timeline);

        mShareLayout = findViewById(R.id.share_layout);

        mShareWeiboImg = (ImageView) findViewById(R.id.share_weibo_img);
        mShareWechatImg = (ImageView) findViewById(R.id.share_wechat_img);
        mShareTimelineImg = (ImageView) findViewById(R.id.share_timeline_img);

        mShareLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manageShareLayout(false);
            }
        });

        mShareTimeline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare(ShareType.TIMELINE);
            }
        });

        mShareWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare(ShareType.WEIBO);
            }
        });

        mShareWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare(ShareType.WECHAT);
            }
        });

        mShareWeiboImg.setImageResource(R.drawable.icon_weibo);
        mShareWechatImg.setImageResource(R.drawable.icon_wechat);
        mShareTimelineImg.setImageResource(R.drawable.icon_pyq);

        mWeb = (WebView) findViewById(R.id.web_ad);
        mTopbar = findViewById(R.id.topbar);

        int statusHeight = SysUtil.getStatusHeight(this);
        if(statusHeight > 0)
            mTopbar.setPadding(0, statusHeight, 0, 0);

        mWeb.addJavascriptInterface(new AubeJavascriptInterface(new AubeJavascriptInterface.H5Interface() {
            @Override
            public void doNativeShare(final String title, final String content, final String picUrl, final String url, final String weiboPic, final String weiboContent) {
                mWeb.post(new Runnable() {
                    @Override
                    public void run() {
                        if(mShareHelper == null)
                            mShareHelper = new H5ShareHelper(that, title, content, picUrl, url, weiboPic, weiboContent, new H5ShareHelper.IShareBitmapListener() {

                                @Override
                                public void onResponse(final ShareModule shareModule) {
                                    manageShareLayout(false);
                                    doShare(shareModule);
                                }
                            });
                        manageShareLayout(true);
                    }
                });
            }
        }), AubeJavascriptInterface.NAME);

        WebSettings webSettings = mWeb.getSettings();

        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        mWeb.setWebViewClient(new WebViewClient() {
            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                dontResend.sendToTarget();
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            }
        });
        mWeb.setWebChromeClient(new WebChromeClient());

        if(doPost) {
            mWeb.postUrl(addSource(url), appendMemberArgs().getBytes());
        } else {
            mWeb.loadUrl(addSource(url));
        }
    }

    private void manageShareLayout(final boolean show) {
        ValueAnimator anim = ValueAnimator.ofFloat(show ? 0 : 1, show ? 1 : 0);
        anim.setDuration(400);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();

                mShareLayout.setAlpha(value);
                mShareWechat.setAlpha(value);
                mShareWeibo.setAlpha(value);
                mShareTimeline.setAlpha(value);

                if(show) {
                    float translationY = mShareWechat.getHeight() * (1-value);
                    mShareWechat.setTranslationY(translationY);
                    mShareWeibo.setTranslationY(translationY);
                    mShareTimeline.setTranslationY(translationY);
                }
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(!show) {
                    mShareLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                if(show) {
                    mShareLayout.setAlpha(0f);
                    mShareWechat.setAlpha(0f);
                    mShareWeibo.setAlpha(0f);
                    mShareTimeline.setAlpha(0f);
                    mShareLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        anim.start();
    }

    private void toShare(final int type) {
        manageShareLayout(false);

        if(mShareHelper != null)
            mShareHelper.toShare(type);
    }

    private String addSource(String url) {
        if(url.contains("source="))
            return url;
        if(url.indexOf("?") > 0)
            url += "&source=app";
        else
            url += "?source=app";
        return url;
    }

    /**
     * 传递给H5登录信息
     * @return
     */
    private String appendMemberArgs() {
        return "userid=" + UserUtil.getMemberId() + "&memberToken=" + UserUtil.getMemberEncode() + "deviceid=" + AppUtil.getDeviceId(getBaseContext());
    }

    public void finish() {
        super.finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(mShareLayout.getVisibility() == View.VISIBLE) {
                manageShareLayout(false);
                return true;
            }
            if((mWeb != null && mWeb.canGoBack())) {
                mWeb.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
